package database

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"log"
	"time"
	"openapi.itspire.cn/config"
)

var Ins *gorm.DB
var dsn string
var err error

func init() {
	switch config.Conf.Database.Driver {
		case "mysql":
			dsn = fmt.Sprintf("%s:%s@%s(%s:%d)/%s",
				config.Conf.Database.User,
				config.Conf.Database.Password,
				config.Conf.Database.Protocol,
				config.Conf.Database.Host,
				config.Conf.Database.Port,
				config.Conf.Database.Name,
			)
		default: log.Fatalf("invalid db driver %v\n", config.Conf.Database.Driver)
	}

	Ins, err = gorm.Open(config.Conf.Database.Driver, dsn)
	if err != nil {
		log.Fatalf("Open "+ config.Conf.Database.Driver +" failed. %v\n", err)
	}
	Ins.DB().SetConnMaxLifetime(100 * time.Second)  //最大连接周期，超过时间的连接就close
	Ins.DB().SetMaxOpenConns(100)   //设置最大连接数
	Ins.DB().SetMaxIdleConns(0)    //设置闲置连接数
	//设置全局表名禁用复数
	Ins.SingularTable(true)

	gorm.DefaultTableNameHandler = func (db *gorm.DB, defaultTableName string) string  {
		return "it_" + defaultTableName
	}
}